//
//  AuthViewController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/4/23.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
//用户认证
class AuthViewController: BaseController {
    var flag = 0//标识
    var user_id : String = ""
    var authTableView:UITableView! //数据表格
    var carPhoto_1:String = ""
    var carPhoto_2:String = ""
    var carPhoto_3:String = ""
    var carPhoto_4:String = ""
    var cell:AuthTableViewCell!
    override func viewDidLoad(){
        super.viewDidLoad()
        setupNavBar(title: "实名认证", isback: true, appearWay: 2, isright: false)//自定义导航
        authTableView=UITableView.init(frame: CGRect(x:0, y:kNavigationBarH+kStatusBarH, width: kScreenW, height: kScreenH-kNavigationBarH - kStatusBarH), style:.plain)
        authTableView.delegate=self;//实现代理
        authTableView.dataSource=self;//实现数据源
        authTableView.rowHeight = 6*cellH + 104 + 4*oImgH
        authTableView.register(AuthTableViewCell.self, forCellReuseIdentifier: "authCellID")
        authTableView.layer.accessibilityScroll(.down)
        self.view.addSubview(authTableView)
        if reachability.isReachable {
           loadAuthInfo()//查询认证信息
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
}
extension AuthViewController{
    func choicePicture(sender: UIButton){
        self.flag = sender.tag
        centerY = sender.convert(sender.bounds, to: toast.container).origin.y
        let alert = UIAlertController()
        let cleanAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler:nil)
        let photoAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
           self.cameraFunc()
        }
        let choseAction = UIAlertAction(title: "从手机相册选择", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            self.photoFunc()
        }
        alert.addAction(cleanAction)
        alert.addAction(photoAction)
        alert.addAction(choseAction)
        self.present(alert, animated: true, completion: nil)
    }
    //调用相机
    func cameraFunc(){
        //初始化图片控制器
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.camera
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: nil)
        }else{
            print("读取相册失败")
        }
    }
    //调用相册
    func photoFunc(){
        //初始化图片控制器
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: nil)
        }else{
            print("读取相册失败")
        }
    
    }
    //提交认证按钮
    func submitUserAuthClick() {
        if "" ==  cell.realNameText.text!{
            checkAlertFun(message: "请输入真实姓名！")
        }else if "" == cell.codeText.text!{
            checkAlertFun(message: "请输入身份证号码！")
        } else if "" == self.carPhoto_1 || "" == self.carPhoto_2 || "" == self.carPhoto_3 || "" == self.carPhoto_4{
            checkAlertFun(message: "请选择证件照片！")
        }else{
            submitUserAuth()
        }
    }
    //提交认证信息
    func submitUserAuth() {
        if reachability.isReachable {
            let parameter:[String:Any] = [
                "realName":cell.realNameText.text!,
                "cardNum":cell.codeText.text!,
                "referral":cell.referralText.text!,
                "carPhoto_1":self.carPhoto_1,
                "carPhoto_2":self.carPhoto_2,
                "carPhoto_3":self.carPhoto_3,
                "carPhoto_4":self.carPhoto_4
            ]
            Alamofire.request("\(projectUrl)/user/auth/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)",method:.post, parameters:parameter,headers:headers).responseJSON { (response) in
                let jsonString = response.result.value!
                let jsonDate = JSON(jsonString)
                if jsonDate["success"] == true {
                    let alertController = UIAlertController(title: alertTitle, message: "认证信息提交成功！", preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "确定", style: .default, handler:{
                        (UIAlertAction) -> Void in
                        self.navigationController?.popViewController(animated: true)
                    })
                    alertController.addAction(okAction)
                    self.present(alertController, animated: true, completion: nil)
                }else{
                    self.failOperNoticeFun(code: jsonDate["rcode"].rawString()!, message: jsonDate["rdata"].rawString()!)
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //查询认证信息
    func loadAuthInfo(){
        let urlString = "\(projectUrl)/user/auth/detail/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
        Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
            if response.result.isSuccess{
                let json = JSON(response.result.value as! [String : AnyObject])
                if json["success"] == true {
                    if(json["rdata"]["authStatus"].exists()){
                        let authStatus = json["rdata"]["authStatus"].rawString()
                        self.setAuthValue(cardNum: json["rdata"]["cardNum"].rawString()!, realName: json["rdata"]["realName"].rawString()!, referral: json["rdata"]["referral"].rawString()!, carPhoto_1: json["rdata"]["carPhoto_1"].rawString()!, carPhoto_2: json["rdata"]["carPhoto_2"].rawString()!, carPhoto_3: json["rdata"]["carPhoto_3"].rawString()!, carPhoto_4: json["rdata"]["carPhoto_4"].rawString()!)
                        if authStatus == "0" {
                            self.cell.checkState.text = "待审核"
                            self.cell.realNameText.isEnabled = false
                            self.cell.codeText.isEnabled = false
                            self.cell.referralText.isEnabled = false
                            self.cell.btn1.isEnabled = false
                            self.cell.btn2.isEnabled = false
                            self.cell.btn3.isEnabled = false
                            self.cell.btn4.isEnabled = false
                            self.cell.submitBtn.isEnabled = false
                            self.cell.submitBtn.backgroundColor = UIColor.lightGray
                        }else if authStatus == "1" {
                            self.cell.checkState.text = "已认证"
                            self.cell.realNameText.isEnabled = false
                            self.cell.codeText.isEnabled = false
                            self.cell.referralText.isEnabled = false
                            self.cell.btn1.isEnabled = false
                            self.cell.btn2.isEnabled = false
                            self.cell.btn3.isEnabled = false
                            self.cell.btn4.isEnabled = false
                            self.cell.submitBtn.isEnabled = false
                            self.cell.submitBtn.backgroundColor = UIColor.lightGray
                        }else if authStatus == "2" {
                            self.cell.checkState.text = "认证失败"
                        }
                    }else{
                        self.cell.checkState.text = "未认证"
                    }
                }else{
                    self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                }
            }
            else{
                print(response.result.error!) //输出错误日志
            }
        }
    }
    func setAuthValue(cardNum:String,realName:String,referral:String,carPhoto_1:String,carPhoto_2:String,carPhoto_3:String,carPhoto_4:String){
        self.cell.codeText.text = cardNum
        self.cell.realNameText.text = realName
        self.cell.referralText.text = referral
        self.carPhoto_1 = carPhoto_1
        self.carPhoto_2 = carPhoto_2
        self.carPhoto_3 = carPhoto_3
        self.carPhoto_4 = carPhoto_4
        self.cell.btn1.sd_setBackgroundImage(with: URL.init(string: "\(projectUrl)/file/download/\(self.carPhoto_1)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"), for: .normal)
        self.cell.btn2.sd_setBackgroundImage(with: URL.init(string: "\(projectUrl)/file/download/\(self.carPhoto_2)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"), for: .normal)
        self.cell.btn3.sd_setBackgroundImage(with: URL.init(string: "\(projectUrl)/file/download/\(self.carPhoto_3)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"), for: .normal)
        self.cell.btn4.sd_setBackgroundImage(with: URL.init(string: "\(projectUrl)/file/download/\(self.carPhoto_4)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"), for: .normal)
    }
}
extension AuthViewController:UITableViewDataSource, UITableViewDelegate{
    //表头部高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10.0
    }
    //底部高度
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        return 0.01
    }
    //行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    //cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        cell = tableView.dequeueReusableCell(withIdentifier: "authCellID") as? AuthTableViewCell
        if cell == nil {
            cell = AuthTableViewCell(style: UITableViewCellStyle.default,reuseIdentifier: "authCellID")
        }
        return cell!
    }
}
extension AuthViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //选择图片成功后代理
    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [String : Any]) {
        //显示的图片
        let image:UIImage =  info[UIImagePickerControllerOriginalImage] as! UIImage
        if reachability.isReachable {
            uploadImage(img: image)//上传图片到服务器
            picker.dismiss(animated: true, completion: nil)//图片控制器退出
            toast.showLoadingView(x: oLabelW + oImgW + 10, y: centerY)
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //上传图片
    func uploadImage(img:UIImage){
        let toUrl = "\(projectUrl)/file/upload/userauth/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
        let imageData = UIImageJPEGRepresentation(img, 1.0)!
        //使用Alamofire上传
        Alamofire.upload(multipartFormData: { (mult) in
            mult.append(imageData, withName: "file", fileName: "userauth\(self.flag).png", mimeType: "image/png")
        }, to: toUrl, encodingCompletion: { (result) in
            switch result {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    let jsonString = response.result.value!
                    let jsonDate = JSON(jsonString)
                    if jsonDate["success"] == true {
                        let photoID = jsonDate["rdata"].rawValue as! String
                        let url = "\(projectUrl)/file/download/\(photoID)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
                        if(1 == self.flag){
                            self.carPhoto_1 = photoID
                            self.cell.btn1.sd_setBackgroundImage(with: URL.init(string: url), for: .normal)
                        }
                        if(2 == self.flag){
                            self.carPhoto_2 = photoID
                            self.cell.btn2.sd_setBackgroundImage(with: URL.init(string: url), for: .normal)
                        }
                        if(3 == self.flag){
                            self.carPhoto_3 = photoID
                            self.cell.btn3.sd_setBackgroundImage(with: URL.init(string: url), for: .normal)
                        }
                        if(4 == self.flag){
                            self.carPhoto_4 = photoID
                            self.cell.btn4.sd_setBackgroundImage(with: URL.init(string: url), for: .normal)
                        }
                    }else{
                        self.failOperNoticeFun(code: jsonDate["rcode"].rawString()!, message: jsonDate["rdata"].rawString()!)
                    }
                    toast.closeWin()
                }
            case .failure(let encodingError):
                print("ERROR RESPONSE: \(encodingError)")
            }
        })
    }
}
